package com.centanet.framework.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

import com.centanet.framework.interfaces.ICompressResult;
import com.centanet.framework.interfaces.IProgressRequestListener;
import com.centanet.framework.interfaces.IUploadResult;
import com.centanet.framework.model.UploadModel;
import com.centanet.framework.task.ImageCompressTask;
import com.centanet.framework.task.StringUploadTask;
import com.centanet.framework.utils.ExternalCacheDirUtil;
import com.centanet.framework.utils.OkHttpUtil;
import com.centanet.framework.utils.ProgressHelper;
import com.orhanobut.logger.Logger;
import com.squareup.okhttp.Headers;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.RequestBody;

import java.io.File;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 上传
 * <p>
 * imageCompressType 压缩方式 0：原图；300：不超过300K；类推
 * <p>
 */
public class UploadService extends Service {

    private final static String TAG = "UploadService";
    private static final String AGENCY_PIC_URL = "http://10.5.10.143:3322/image/upload/";//测试上传图片地址

    private OkHttpClient okHttpClient;
    private ExecutorService singleTaskExecutor;//每次执行一个任务线程池
    private UploadBinder uploadBinder = new UploadBinder();
    private String compressDir;//压缩保存目录

    @Override
    public void onCreate() {
        super.onCreate();
        compressDir = ExternalCacheDirUtil.getImageCompressCacheDir(this);
        okHttpClient = OkHttpUtil.getOkHttpClient().clone();
        okHttpClient.setConnectTimeout(15, TimeUnit.SECONDS);
        okHttpClient.setWriteTimeout(15, TimeUnit.SECONDS);
        okHttpClient.setReadTimeout(15, TimeUnit.SECONDS);
        singleTaskExecutor = Executors.newSingleThreadExecutor();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 只做压缩
     */
    private void compressOnly(ArrayList<String> list, int imageCompressType) {
        new ImageCompressTask(compressDir, list, imageCompressType, new ICompressResult() {
            @Override
            public void result(ArrayList<String> result) {
            }
        }).execute();
    }

    /**
     * 统一压缩
     */
    private void compress(ArrayList<String> list, int imageCompressType) {
        new ImageCompressTask(compressDir, list, imageCompressType, new ICompressResult() {
            @Override
            public void result(ArrayList<String> result) {
                for (String s : result) {
                    addTask(s);
                }
            }
        }).execute();
    }

    /**
     * 添加任务
     */
    private void addTask(String path) {
        final File file = new File(path);
        final RequestBody requestBody = new MultipartBuilder()
                .type(MultipartBuilder.FORM)
                .addPart(Headers.of("Content-Disposition",
                        "form-data; name=\"pic\";filename=\"" + file.getName() + ".jpg\"")
                        , RequestBody.create(MediaType.parse("application/octet-stream"), file))
                .build();
        new StringUploadTask(okHttpClient, AGENCY_PIC_URL, path, ProgressHelper.addProgressRequestListener(requestBody, new IProgressRequestListener() {
            @Override
            public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
                Logger.t(TAG).d("progress write : %d - sum : %d - progrss : %d - done : %b", bytesWritten, contentLength, bytesWritten * 100 / contentLength, done);
            }
        }), new IUploadResult<String>() {
            @Override
            public void result(UploadModel<String> uploadModel) {
                Logger.t(TAG).d("upload result : %b url : [%s]\npath : [%s]", uploadModel.isSuccess(), uploadModel.getResponse(), uploadModel.getPath());
            }
        }).executeOnExecutor(singleTaskExecutor);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return uploadBinder;
    }

    public class UploadBinder extends Binder {

        /**
         * @param list 原图路径集合
         */
        public void upload(ArrayList<String> list) {
            compress(list, 300);
        }

        /**
         * @param list              原图路径集合
         * @param imageCompressType 压缩类型
         */
        public void upload(ArrayList<String> list, int imageCompressType) {
            compress(list, imageCompressType);
        }

        public void onlyCompress(ArrayList<String> list) {
            compressOnly(list, 300);
        }
    }
}
